const express = require("express");
const multer = require("multer");
const fs = require("fs");
const upload = multer({
  dest: "uploads/",
  fileFilter: (req, file, callback) => {
    try {
      if (req.files) {
        const extname = file.originalname.split(".").reverse()[0];
        const ext = ["png", "jpg", "jpeg", "bmp", "gif", "svg"];
        if (ext.indexOf(extname.toLowerCase()) !== -1) {
          callback(null, true);
        } else {
          req.filterError = {
            filterMsg: "只能上传png,jpg,jpeg,bmp,gif,svg格式的文件",
          };
          callback(null, false);
        }
      } else callback(null, false);
    } catch (error) {
      callback(new Error("上传服务发生异常，稍后再试," + error));
    }
  },
  limits: { fileSize: 1024 * 1024 * 10 },
}).any();

const router = express.Router();

router.post("/file", (req, res) => {
  upload(req, res, function (err) {
    if (err instanceof multer.MulterError) {
      return res.status(200).json({
        message: "发生异常",
        data: err,
      });
    } else if (err) {
      return res.status(200).json({
        message: "发生异常",
        data: err,
      });
    }

    // 未发生异常开始的操作
    if (req.files.length > 0) {
      const filename =
        req.files[0].path + "." +
        req.files[0].originalname.split(".").reverse()[0];
      fs.rename(req.files[0].path, filename, function (err) {
        if (err) {
          res.status(200).json({
            message: "上传异常",
            data: err,
          });
        } else {
          res.status(200).json({
            message: "上传成功",
            data: filename,
          });
        }
      });
    } else {
      res.status(200).json({
        message: "上传异常",
        data:req.filterError
      });
    }
  });
});

module.exports = router;
